package com.ocom.webapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.EntityXfAccountType;
import com.ocom.common.entity.human.EntityPersonTag;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.webapi.ExcelAddPersonVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.MqSimpleService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.service.StaffPageService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Service
public class StaffPageServiceImpl implements StaffPageService {


    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    MqSimpleService mqSimpleService;

    @Override
    public Result StaffPageImport(Long comId,String areaGroop, MultipartFile file) {

        //        1、用HSSFWorkbook打开或者创建“Excel文件对象”
        //        2、用HSSFWorkbook对象返回或者创建Sheet对象
        //        3、用Sheet对象返回行对象，用行对象得到Cell对象
        //        4、对Cell对象读写。
        //获得文件名
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

//        List<EntityPersonnelInfo> entityPersonnelInfos = new ArrayList<>();
        List<Map> errList = new ArrayList<>();
        Gson gson =new Gson();


        Long timestamp = System.currentTimeMillis();
        Map<String,Object> map1=new HashMap<>();
        map1.put("key","ImportErr:detail:"+comId+":"+timestamp);
        map1.put("type",3);
        map1.put("name","人员批量导入");
        map1.put("timestamp",timestamp);
        map1.put("datetime", DateUtil.getDateTime());
        redisUtil.leftPush("ImportErr:"+comId,map1,86400l);


        List<EntityDeptInfo> list= new ArrayList<>();
        //获取完整部门树
        Result result2 = humanClientService.getDeptList(comId,0l,1);

        if(result2.getCode()!=200){
            return ResultUtil.error(ResultEnum.Err_302);
        }

        list = JSON.parseArray(JSON.toJSONString(result2.getData()), EntityDeptInfo.class);

        //账户类型列表
        Result GetXFAccountTypeResult = payConfigClientService.GetXFAccountType(comId);
        if (200 != GetXFAccountTypeResult.getCode()) {
            return ResultUtil.error(ResultEnum.Err_302);
        }
        List<EntityXfAccountType> xfAccountTypes = JSON.parseArray(JSON.toJSONString(GetXFAccountTypeResult.getData()), EntityXfAccountType.class);
        HashMap<Integer, EntityXfAccountType> xfAccountTypeHashMap = xfAccountTypes.stream().collect(Collectors.toMap(e -> e.getAccTypeId(), e -> e, (e, e1) -> {
            return e1;
        }, HashMap::new));
        //标签列表
        Result perTagResult = humanClientService.getPerTag(comId, 1, 0);
        if (200 != perTagResult.getCode()) {
            return ResultUtil.error(ResultEnum.Err_302);
        }
        List<EntityPersonTag> entityPersonTags = JSON.parseArray(JSON.toJSONString(perTagResult.getData()), EntityPersonTag.class);
        HashMap<String, EntityPersonTag> tagHashMap = entityPersonTags.stream().collect(Collectors.toMap(e -> e.getTagName(), e -> e, (e, e1) -> {
            return e1;
        }, HashMap::new));


        for (int i = 1; i < rows+1; i++) {
            MapKey mapKey = new MapKey();
            EntityPersonnelInfo entityPersonnelInfo = new EntityPersonnelInfo();
            Map<String, Object> map = new HashMap<>();
            entityPersonnelInfo.setComId(SecurityUtils.getYoCiUser().getComId());
            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {

                String errMsg = "";

                // **读取cell**
                //姓名
                entityPersonnelInfo.setPName("");
                String pName = JSON.toJSONString(getCellValue(row.getCell(0))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pName) && !pName.equals("null")){
                    entityPersonnelInfo.setPName(pName);
                }else{
                    errMsg += "姓名为空,";
                }


                // 性别(男/女)
                String pSex = JSON.toJSONString(getCellValue(row.getCell(1))).replace("\"", "").replace("\\t", "");
                if (pSex.equals("男")) {
                    entityPersonnelInfo.setPSex(0);
                } else if (pSex.equals("女")) {
                    entityPersonnelInfo.setPSex(1);
                }

                // 人员编号
                entityPersonnelInfo.setPCode("");
                String pCode = JSON.toJSONString(getCellValue(row.getCell(2))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pCode) && !pCode.equals("null")){
                    entityPersonnelInfo.setPCode(pCode);
                }else{
                    errMsg += "编号为空,";
                }



                // 人员编号

                String deptName = JSON.toJSONString(getCellValue(row.getCell(3))).replace("\"", "").replace("\\t", "");


                String[] deptNameSplit = deptName.split("/");

                if(deptNameSplit.length<=0){
                    map.put(mapKey.getKey_pName(),pName);
                    map.put(mapKey.getKey_deptName(),deptName);
                    map.put(mapKey.getKey_pIdentity(), "");
                    errList.add(map);
                    continue;
                }else {
                    Long realDeptId=0l;
                    Long parentDeptId=0l;

                    outterLoop: for (String ndeptName:deptNameSplit){
                        Boolean exist=false;
                        for (EntityDeptInfo entityDeptInfo:list){
                            //匹配到名称
                            if(entityDeptInfo.getDeptName().equals(ndeptName) &&
                                    entityDeptInfo.getParentDeptId().equals(parentDeptId)){
                                exist=true;
                                parentDeptId = entityDeptInfo.getDeptId();
                                realDeptId = entityDeptInfo.getDeptId();
                            }
                        }
                        if(!exist){
                            map.put(mapKey.getKey_pName(),pName);
                            map.put(mapKey.getKey_deptName(),deptName);
                            map.put(mapKey.getKey_pIdentity(), "");
                            errList.add(map);
                            realDeptId= 0l;

                            errMsg += "部门未匹配到,";
                            break  outterLoop;
                        }
                    }

                    entityPersonnelInfo.setDeptId(realDeptId);
                }




//                Long deptID = null;
//                Result result = humanClientService.GetDeptInfo(comId, deptID, deptName);
//                if (result.getCode() == 200) {
//                    List<EntityDeptInfo> entityDeptInfos = JSON.parseArray(JSON.toJSONString(result.getData()), EntityDeptInfo.class);
//                    if (entityDeptInfos.size() == 0) {
//                        entityPersonnelInfo.setDeptId(0L);
//                    }
//                    for (EntityDeptInfo entityDeptInfo : entityDeptInfos) {
//                        if (entityDeptInfo.getDeptName().equals(deptName)  || entityDeptInfo.getGrade().equals(grade)) {
//                            entityPersonnelInfo.setDeptId(entityDeptInfo.getDeptId());
//                        }
//                    }
//                }


                //人员密码
                String pPwd= JSON.toJSONString(getCellValue(row.getCell(4))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPwd) && !pPwd.equals("null")){
                    entityPersonnelInfo.setPPwd(pPwd);
                }

                // 联系电话
                entityPersonnelInfo.setPPhone("");
                String pPhone = JSON.toJSONString(getCellValue(row.getCell(5))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPhone) && !pPhone.equals("null")){
                    entityPersonnelInfo.setPPhone(pPhone);
                }else{
                    errMsg += "电话为空,";
                }


                // 身份证号码
                entityPersonnelInfo.setPIdentity("");
                String pIdentity = JSON.toJSONString(getCellValue(row.getCell(6))).replace("\"", "").replace("\\t", "");
                if (pIdentity.length() != 18 || pIdentity.isEmpty() || pIdentity.equals("null")) {
                    map.put(mapKey.getKey_pName(),pName);
                    map.put(mapKey.getKey_deptName(),deptName);
                    map.put(mapKey.getKey_pIdentity(), pIdentity);
                    errList.add(map);
                    errMsg += "身份证为空或长度不对,";
                }else {
                    if (!IdentificationCodeUtil.isIdentityCode(pIdentity)){
                        map.put(mapKey.getKey_pName(),pName);
                        map.put(mapKey.getKey_deptName(),deptName);
                        map.put(mapKey.getKey_pIdentity(), pIdentity);
                        errList.add(map);
                        errMsg += "身份证校验不过,";
                    }else{
                        entityPersonnelInfo.setPIdentity(pIdentity);
                        Map<String,String> mapUser= new HashMap<>();
                        mapUser.put("name",pName);
                        mapUser.put("identitycard_No",pIdentity);
                        redisUtil.leftPush("timerCompany:"+comId+":0",gson.toJson(map),82800l);
                    }
                }
            // 住址
                entityPersonnelInfo.setPAddress("");
                String pAddress = JSON.toJSONString(getCellValue(row.getCell(7))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pAddress) && !pAddress.equals("null")){
                    entityPersonnelInfo.setPAddress(pAddress);
                }

//                // 人脸图像地址
                entityPersonnelInfo.setPPhotoUrl("");
                String pPhotoUrl = JSON.toJSONString(getCellValue(row.getCell(8))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(pPhotoUrl) && !pPhotoUrl.equals("null")){
                    entityPersonnelInfo.setPPhotoUrl(pPhotoUrl);
                }


                //账户类型
                String excelAccTypeId = JSON.toJSONString(getCellValue(row.getCell(9))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(excelAccTypeId) && !excelAccTypeId.equals("null")){
                    EntityXfAccountType xfAccountType = xfAccountTypeHashMap.get(Integer.valueOf(StringUtils.trim(excelAccTypeId, " ")));
                    if (null != xfAccountType) {
                        entityPersonnelInfo.setAccTypeId(xfAccountType.getAccTypeId());
                    }
                }

                //多个标签用|分隔
                String excelPerTag = JSON.toJSONString(getCellValue(row.getCell(10))).replace("\"", "").replace("\\t", "");
                if (StringUtils.isNotEmpty(excelPerTag) && !excelPerTag.equals("null")){
                    List<EntityPersonTag> tags = new ArrayList<>();
                    String[] split = StringUtils.trim(excelPerTag, " ").split("\\|");
                    for (String tag : split) {
                        EntityPersonTag entityPersonTag = tagHashMap.get(tag);
                        if (null != entityPersonTag) {
                            tags.add(entityPersonTag);
                        }
                    }
                    entityPersonnelInfo.setPerTags(tags);
                }

            }


            if(CommonUtil.isNull(entityPersonnelInfo.getPAddress())){
                entityPersonnelInfo.setPAddress(null);
            }

            if(CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl())){
                entityPersonnelInfo.setPPhotoUrl(null);
            }

            List<EntityPersonnelInfo> entityPersonnelInfos = new ArrayList<>();
            entityPersonnelInfos.add(entityPersonnelInfo);

            ExcelAddPersonVo excelAddPersonVo =new ExcelAddPersonVo();
            excelAddPersonVo.setTimestamp(timestamp);
            excelAddPersonVo.setComId(comId);
            excelAddPersonVo.setAreaGroop(areaGroop);
            excelAddPersonVo.setPersonnelInfos(entityPersonnelInfos);
//            humanClientService.ImportUserInfo(excelAddPersonVo);
            mqSimpleService.ImportPerson(excelAddPersonVo);

        }

//        ExcelAddPersonVo excelAddPersonVo =new ExcelAddPersonVo();
//        excelAddPersonVo.setTimestamp(timestamp);
//        excelAddPersonVo.setComId(comId);
//        excelAddPersonVo.setAreaGroop(areaGroop);
//        excelAddPersonVo.setPersonnelInfos(entityPersonnelInfos);
//        humanClientService.ImportUserInfo(excelAddPersonVo);

//        humanClientService.ImportUserInfo(comId,timestamp,areaGroop, entityPersonnelInfos);


        return ResultUtil.success(errList);
    }

}
